<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>

<head>
    <title>员工列表</title>
    <%
        pageContext.setAttribute("APP_PUTH", request.getContextPath());
    %>
    <link href="${APP_PUTH}/static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <%--    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>--%>
</head>
<body>
<!-- 员工的修改 -->
<div class="modal fade" id="emp_update" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="control-label col-md-2">empName:</label>
                        <div class="col-md-10">
                            <p class="form-control-static" id="empName_update_input"></p>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-2">email:</label>
                        <div class="col-md-10">
                            <input type="text" class="form-control" name="email" id="email_update_input"
                                   placeholder="zzl@qq.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-2">gender:</label>
                        <div class="col-md-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender_update_input1" value="M" checked="checked">
                                男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender_update_input2" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-2">deptName:</label>
                        <div class="col-md-4">
                            <select class="form-control" name="dId" id="dept_update_select">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_update_btn">修改</button>
            </div>
        </div>
    </div>
</div>
<!-- 员工的添加 -->
<div class="modal fade" id="emp_add" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="control-label col-md-2">empName:</label>
                        <div class="col-md-10">
                            <input type="text" class="form-control" name="empName" id="empName_add_input"
                                   placeholder="empName">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-2">email:</label>
                        <div class="col-md-10">
                            <input type="text" class="form-control" name="email" id="email_add_input"
                                   placeholder="zzl@qq.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-2">gender:</label>
                        <div class="col-md-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender_and_input1" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender_and_input2" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-2">deptName:</label>
                        <div class="col-md-4">
                            <select class="form-control" name="dId" id="dept_add_select">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>
<%--index--%>
<div class="container ">
    <%--标题 --%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSM-CRUD</h1>
        </div>
    </div>
    <%--按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button class="btn btn-primary" id="emp_add_btn">添加</button>
            <button class="btn btn-danger" id="emp_del_all">删除</button>
        </div>
    </div>
    <%--表格--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <thead>
                <tr>
                    <th><input type="checkbox" id="check_all"></th>
                    <th>#</th>
                    <th>empName</th>
                    <th>gender</th>
                    <th>email</th>
                    <th>deptName</th>
                    <th>操作</th>
                </tr>
                </thead>

                <tbody>

                </tbody>
            </table>
        </div>
    </div>
    <%--分页--%>
    <div class="row">
        <%--当前显示的信息--%>
        <div class="col-md-6" id="page_info_area">
        </div>
        <%--分页条--%>
        <%--分页条--%>
        <div class="col-md-6" id="page_info_item">

        </div>

    </div>
</div>
</body>
<script src="${APP_PUTH}/static/js/jquery.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="${APP_PUTH}/static/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
    var totalResult = 0;
    var currPage = 1;
    $(function () {
        to_page(1);
    });

    function to_page(pn) {
        $.ajax({
            url: "${APP_PUTH}/emps",
            data: "pn=" + pn,
            type: "get",
            success: function (result) {
                build_emp_table(result);
                build_emp_info(result);
                build_emp_nav(result);
            }
        });
    }

    //表格信息
    function build_emp_info(result) {
        currPage = result.extend.pageInfo.pageNum;
        $("#page_info_area").empty();
        $("#page_info_area").append("当前" + result.extend.pageInfo.pageNum + "页,共有" +
            result.extend.pageInfo.pages + "页,共有" + result.extend.pageInfo.total + "条记录");
        totalResult = result.extend.pageInfo.total;
    }

    //表格条目
    function build_emp_nav(result) {
        $("#page_info_item").empty();
        var ul = $("<ul></ul>").addClass("pagination");
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#"));
        var prePageLi = $("<li></li>").append($("<a></a>").append($("<span></span>").append("&laquo;")));
        if (result.extend.pageInfo.hasPreviousPage == false) {
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        } else {
            firstPageLi.click(function () {
                to_page(1);
            });
            prePageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum - 1);
            });
        }
        ul.append(firstPageLi).append(prePageLi);
        var nextPageLi = $("<li></li>").append($("<a></a>").append($("<span></span>").append("&raquo;")));
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href", "#"));
        if (result.extend.pageInfo.hasNextPage == false) {
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        } else {
            lastPageLi.click(function () {
                to_page(result.extend.pageInfo.pages);
            });
            nextPageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum + 1);
            });
        }
        $.each(result.extend.pageInfo.navigatepageNums, function (index, item) {
            var itemLi = $("<li></li>").append($("<a></a>").append(item));
            if (item == result.extend.pageInfo.pageNum) {
                itemLi.addClass("active");
            }
            itemLi.click(function () {
                to_page(item);
            });
            ul.append(itemLi);
        });
        ul.append(nextPageLi).append(lastPageLi);
        var nav = $("<nav></nav>").append(ul).attr("aria-label", "Page navigation");
        nav.appendTo("#page_info_item");
    }

    //构建表格
    function build_emp_table(result) {
        $("#emps_table tbody").empty();
        var emps = result.extend.pageInfo.list;
        $.each(emps, function (index, emp) {
            var chechBoxTd = $("<td><input type='checkbox' class='checkbox_item'></td>")
            var empIDTd = $("<td></td>").append(emp.empId);
            var empNameTd = $("<td></td>").append(emp.empName);
            var empGenderTd = $("<td></td>").append((emp.gender == "M" ? "男" : "女"));
            var empEmailTd = $("<td></td>").append(emp.email);
            var empDeptTd = $("<td></td>").append(emp.department.deptName);
            var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
                .append("<span></span>").addClass("glyphicon glyphicon-pencil").append("编辑");
            editBtn.attr("emp_id", emp.empId);
            var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
                .append("<span></span>").addClass("glyphicon glyphicon-trash").append("删除");
            var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn);

            $("<tr></tr>").append(chechBoxTd)
                .append(empIDTd)
                .append(empNameTd)
                .append(empGenderTd)
                .append(empEmailTd)
                .append(empDeptTd)
                .append(btnTd)
                .appendTo("#emps_table tbody");
        });

    }

    //重置表单
    function reset_form(ele) {
        $(ele)[0].reset();
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").text("");
    }

    $("#emp_add_btn").click(function () {
        reset_form("#emp_add form");
        //获取部门信息
        getDepts("#dept_add_select");
        $("#emp_add").modal({
            backdrop: 'static'
        });
    });

    function getDepts(ele) {
        $(ele).empty();
        $.ajax({
            url: "${APP_PUTH}/depts",
            type: "GET",
            success: function (result) {
                $.each(result.extend.depts, function () {
                    var optionEle = $("<option></option>").append(this.deptName).attr("value", this.deptId);
                    $(ele).append(optionEle);
                });

            }
        });
    }

    //数据校验
    function validation_add_form() {
        var empName = $("#empName_add_input").val();
        var regName = /(^[a-zA-Z0-9_-]{6,15}$)|(^[\u4e00-\u9fa5]{2,5})/;
        if (!regName.test(empName)) {
            show_validate_msg("#empName_add_input", "err", "用户名是中文2到5位或者字母6到15位组合");
            return false;
        } else {
            show_validate_msg("#empName_add_input", "success", "");
        }
        ;
        var empEmail = $("#email_add_input").val();
        var regEmail = /^\w+@[a-z0-9]+\.[a-z]{2,4}$/;
        if (!regEmail.test(empEmail)) {
            show_validate_msg("#email_add_input", "err", "邮箱格式不正确");
            return false;
        } else {
            show_validate_msg("#email_add_input", "success", "");
        }
        ;

        return true;
    }

    function show_validate_msg(ele, status, msg) {
        $(ele).parent().removeClass("has-error has-success");
        $(ele).next("span").text("");
        if ("success" == status) {
            $(ele).parent().addClass("has-success");
            $(ele).next("span").text(msg);
        } else if ("err" == status) {
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg);
        }
    }

    $("#empName_add_input").change(function () {
        var empName = this.value;
        $.ajax({

            url: "${APP_PUTH}/checkuser",
            data: "empName=" + empName,
            type: "POST",
            success: function (result) {
                if (result.code == 100) {
                    show_validate_msg("#empName_add_input", "success", result.extend.va_msg);
                    $("#emp_save_btn").attr("ajax-va", "success");
                } else {
                    show_validate_msg("#empName_add_input", "err", result.extend.va_msg);
                    $("#emp_save_btn").attr("ajax-va", "err");
                }
            }
        });
    });
    $("#emp_save_btn").click(function () {

        if (!validation_add_form()) {
            return false;
        }
        if ($(this).attr("ajax-va") == "err") {
            return false;
        }
        $.ajax({
            url: "${APP_PUTH}/emp",
            type: "POST",
            data: $("#emp_add form").serialize(),
            success: function (result) {
                console.log(result)
                if (result.code == 100) {
                    $("#emp_add").modal("hide");
                    to_page(totalResult);
                    alert(result.msg);
                } else if (result.code == 200) {
                    //校验失败 响应失败信息
                    if ("undefine" != result.extend.errorFields.email) {
                        //邮箱校验失败
                        show_validate_msg("#email_add_input", "err", result.extend.errorFields.email);
                    }
                    if ("undefine" != result.extend.errorFields.empName) {
                        //邮箱校验失败
                        show_validate_msg("#empName_add_input", "err", result.extend.errorFields.empName);
                    }
                }

            }
        });
    });

    //修改的逻辑
    //为修改的按钮绑定事件
    $(document).on("click", ".edit_btn", function () {
        getEmp($(this).attr("emp_id"));
        getDepts("#dept_update_select");
        $("#emp_update_btn").attr("emp_id", $(this).attr("emp_id"));
        $("#emp_update").modal({
            backdrop: 'static'
        });

    });
    //删除员工
    $(document).on("click", ".delete_btn", function () {
        var empName = $(this).parents("tr").find("td:eq(2)").text();
        var empId = $(this).parents("tr").find("td:eq(1)").text();
        if (confirm("确定删除" + empName + "吗?")) {
            $.ajax({
                url: "${APP_PUTH}/delete/" + empId,
                type: "GET",
                success: function (result) {
                    alert(result.msg);
                    to_page(currPage);
                }
            });
        }

    });
    //批量删除

    $("#emp_del_all").click(function () {
        var empNames = "";
        var empIds = "";
        $.each($(".checkbox_item:checked"),function () {
           empNames += $(this).parents("tr").find("td:eq(2)").text()+",";
           empIds += $(this).parents("tr").find("td:eq(1)").text()+"-";
        });
        empNames = empNames.substring(0,empNames.length-1);
        empIds = empIds.substring(0,empIds.length-1);
        if (confirm("确定删除"+empNames+"吗")){
            $.ajax({
                url: "${APP_PUTH}/delete/" + empIds,
                type: "GET",
                success: function (result) {
                    alert(result.msg);
                    to_page(currPage);
                }
            });
        }
        // alert(empNames)
    });
    $("#check_all").click(function () {
        //checkBox的全选
        $(".checkbox_item").prop("checked", $(this).prop("checked"));

    });


    $(document).on("click", ".checkbox_item", function () {
        var flag = $(".checkbox_item:checked").length == $(".checkbox_item").length;
        $("#check_all").prop("checked",flag)
    });

    function getEmp(id) {
        $.ajax({
            url: "${APP_PUTH}/emp/" + id,
            type: "GET",
            success: function (result) {
                console.log(result);
                var empDate = result.extend.emp;
                $("#empName_update_input").text(empDate.empName);
                $("#email_update_input").val(empDate.email);
                $("#emp_update input[name=gender]").val([empDate.gender]);
                $("#emp_update select").val([empDate.dId]);
            }
        });
    }

    $("#emp_update_btn").click(function () {
        var empEmail = $("#email_update_input").val();
        var regEmail = /^\w+@[a-z0-9]+\.[a-z]{2,4}$/;
        if (!regEmail.test(empEmail)) {
            show_validate_msg("#email_update_input", "err", "邮箱格式不正确");
            return false;
        } else {
            show_validate_msg("#email_update_input", "success", "");
        }
        ;

        $.ajax({
            url: "${APP_PUTH}/emp/" + $(this).attr("emp_id"),
            type: "PUT",
            data: $("#emp_update form").serialize(),
            success: function (result) {
                alert(result.msg);
                $("#emp_update").modal("hide");
                to_page(currPage);
            }
        });
    });
</script>
</html>
